<template class="firstpage">
  <div>
    <div class="boxMargin">
      <el-row>
        <el-col :span="10">
          <p class="title">商品主图</p>
          <div style="display:flex;">
            <div class="drawing_div">
              <img :src="customData.graphImage" alt="" style="max-width:100%;max-height:100%">
            </div>
            <div style="margin-left:20px;">
              <p>长宽比：1:1</p>
              <p>尺寸：600*600 ~ 1000*1000</p>
              <p>格式：JPG，PNG</p>
              <p>大小：不超过454k</p>
            </div>
          </div>
          <p class="title" style="width: 115px;height:30px;word-wrap:break-word;">{{ customData.graphImageName }}</p>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <p class="title">商品图</p>
          <div class="mainImgStyle">
            <draggable v-model="customData.commodityMap" style="display:flex;flex-wrap: wrap;" chosen-class="chosen" force-fallback="true" group="item" animation="1000">
              <transition-group>
                <div v-for="(item,index) in customData.commodityMap" :key="index" class="item" style="margin:5px;">
                  <div class="drawing_div" style="margin-bottom:10px;">
                    <img v-if="item.displayUrl != undefined && item.displayUrl != null && item.displayUrl != ''" :src="item.displayUrl" alt="" style="max-width:100%;max-height:100%">
                  </div>
                  <p class="title" style="width: 115px;height:30px;word-wrap:break-word;">{{ item.imageName }}</p>
                  <el-button type="danger" class="buttonWidht" size="small" @click="removeImg(item,2)">删除</el-button>
                  <el-button type="primary" style="margin-left:0;margin-top:10px" class="buttonWidht" size="small" @click="previewImg(item)">预览</el-button>
                </div>
              </transition-group>
            </draggable>
          </div>
          <div>
            <div class="drawing_div" style="margin: 5px;float: left;border-radius: 6px;background-color: #fbfdff;width: 136px;height: 136px;-webkit-box-sizing: border-box;box-sizing: border-box;border: 1px dashed #c0ccda;display: -webkit-box;display: -ms-flexbox;display: flex;-webkit-box-pack: center;-ms-flex-pack: center;justify-content: center;-webkit-box-align: center;-ms-flex-align: center;align-items: center;" @click="productBox"><i data-v-90c66e46="" class="el-icon-plus" /></div>
            <div style="margin: 5px;float: left;">
              <p>长宽比：1:1</p>
              <p>尺寸：600*600 ~ 1000*1000</p>
              <p>格式：JPG，PNG</p>
              <p>大小：不超过454k</p>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <p class="title">素材图</p>
          <div style="display:flex;flex-wrap: wrap;">
            <div v-for="(item,index) in customData.materialMap" :key="index" style="margin-right:10px;flex:none;width:136px;height:310px;">
              <div class="drawing_div" style="margin-bottom:10px;">
                <img v-if="item.displayUrl != undefined && item.displayUrl != null && item.displayUrl != ''" :src="item.displayUrl" alt="" style="max-width:100%;max-height:100%">
              </div>
              <p class="title" style="width: 115px;height:30px;word-wrap:break-word;">{{ item.imageName }}</p>
              <el-button type="success" class="buttonWidht" size="small" @click="addImg(item)">添加</el-button>
              <el-button type="danger" style="margin-left:0;margin-top:10px" class="buttonWidht" size="small" @click="removeImg(item,4)">删除</el-button>
              <el-button type="primary" style="margin-left:0;margin-top:10px" class="buttonWidht" size="small" @click="previewImg(item)">预览</el-button>
            </div>
            <div>
              <div class="drawing_div" style="border-radius: 6px;background-color: #fbfdff;width: 136px;height: 136px;-webkit-box-sizing: border-box;box-sizing: border-box;border: 1px dashed #c0ccda;display: -webkit-box;display: -ms-flexbox;display: flex;-webkit-box-pack: center;-ms-flex-pack: center;justify-content: center;-webkit-box-align: center;-ms-flex-align: center;align-items: center;" @click="matertBox"><i data-v-90c66e46="" class="el-icon-plus" /></div>
            </div>
          </div>
          <div>
            <p>长宽比：1:1</p>
            <p>尺寸：600*600 ~ 1000*1000</p>
            <p>格式：JPG，PNG</p>
            <p>大小：不超过454k</p>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: center;">
          <el-button type="success" @click="infoUpdate">保存</el-button>
        </el-col>
      </el-row>
    </div>
    <el-dialog title="预览" class="previewBox" :visible.sync="customData.previewShow" @close="closeDialogs">
      <div id="previews">
        <div style="width:100%;height:563px;box-sizing:border-box;display:flex;background-color: #fbfdff;justify-content: center;align-items: center;">
          <img v-if="customData.previewObj.displayUrl != undefined && customData.previewObj.displayUrl != null && customData.previewObj.displayUrl != ''" :src="customData.previewObj.displayUrl" alt="" style="max-width:100%;max-height:100%">
        </div>
      </div>
    </el-dialog>
    <el-dialog title="商品图" class="previewBox" :visible.sync="dialogData.productBox" style="margin-top: -10vh;">
      <draggable v-model="customData.commodityMap" style="display:flex;flex-wrap: wrap;" chosen-class="chosen" force-fallback="true" group="item" animation="1000">
        <transition-group>
          <div v-for="(item,index) in customData.commodityMap" :key="index" class="item" style="margin:5px;">
            <div class="drawing_div" style="margin-bottom:10px;">
              <img v-if="item.displayUrl != undefined && item.displayUrl != null && item.displayUrl != ''" :src="item.displayUrl" alt="" style="max-width:100%;max-height:100%">
            </div>
            <p class="title" style="width: 115px;height:30px;word-wrap:break-word;">{{ item.imageName }}</p>
            <el-button type="danger" class="buttonWidht" size="small" @click="removeImg(item,2)">删除</el-button>
            <el-button type="primary" style="margin-left:0;margin-top:10px" class="buttonWidht" size="small" @click="previewImg(item)">预览</el-button>
          </div>
        </transition-group>
      </draggable>
      <el-upload
        v-if="customData.commodityMap.length<10"
        ref="commodityMap"
        action
        :multiple="true"
        :show-file-list="false"
        :file-list="customData.uploadFileList"
        :auto-upload="false"
        :on-change="beforeCommodityMapUploadType"
        accept=".png,.jpg"
      >
        <div class="drawing_div" style="margin: 5px;float: left">
          <i class="el-icon-plus" />
        </div>
        <div style="float: left;text-align: left;">
          <p>长宽比：1:1</p>
          <p>尺寸：600*600 ~ 1000*1000</p>
          <p>格式：JPG，PNG</p>
          <p>大小：不超过454k</p>
        </div>
      </el-upload>
      <el-row style="text-align:right">
        <el-col><el-button type="primary" size="small" @click="infoUpdate">确定排序</el-button></el-col>
      </el-row>
    </el-dialog>
    <el-dialog title="素材图" class="previewBox" :visible.sync="dialogData.matertBox" style="margin-top: -10vh;">
      <div style="display:flex;flex-wrap: wrap;">
        <div v-for="(item,index) in customData.materialMap" :key="index" style="margin-right:10px;flex:none;width:136px;height:280px;">
          <div class="drawing_div" style="margin-bottom:10px;">
            <img v-if="item.displayUrl != undefined && item.displayUrl != null && item.displayUrl != ''" :src="item.displayUrl" alt="" style="max-width:100%;max-height:100%">
          </div>
          <p class="title" style="width: 115px;height:30px;word-wrap:break-word;">{{ item.imageName }}</p>
          <el-button type="danger" class="buttonWidht" size="small" @click="removeImg(item,4)">删除</el-button>
          <el-button type="primary" style="margin-left:0;margin-top:10px" class="buttonWidht" size="small" @click="previewImg(item)">预览</el-button>
        </div>
        <el-upload
          ref="materialMap"
          action
          :show-file-list="false"
          :file-list="customData.uploadMaterialFileList"
          :multiple="true"
          :auto-upload="false"
          :on-change="beforeMaterialUploadType"
          accept=".png,.jpg"
        >
          <div class="drawing_div">
            <i class="el-icon-plus" />
          </div>
        </el-upload>
      </div>
      <div>
        <p>长宽比：1:1</p>
        <p>尺寸：600*600 ~ 1000*1000</p>
        <p>格式：JPG，PNG</p>
        <p>大小：不超过454k</p>
      </div>
      <el-row style="text-align:right">
        <el-col><el-button type="primary" size="small" @click="infoUpdate">确定</el-button></el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import _validate from '../../../../../framework/commonJs/wptx_validate'
import _tools from '../../../../../framework/commonJs/wptx_tools'
import { global } from '../../../../../filter/global-api'
import _api from '../../../../../framework/API/generalItem'
import draggable from 'vuedraggable'
const _FUNCTION_NAME = ''
export default {
  components: {
    draggable // 当前页面注册组件
  },
  filters: {},
  data() {
    return {
      tableData: [],
      searchData: {
      },
      searchDataBuffer: {
      },
      pageData: {
        pageNo: 1,
        pageSize: 10,
        total: 1,
        pageSizes: [10, 20, 50, 100]
      },
      dialogData: {
        productBox: false,
        matertBox: false
      },
      historyData: {},
      infoData: {},
      customData: {
        activeName: 'first',
        basic: true,
        graphImage: '',
        graphImageName: '',
        drawingImage: '',
        masterItemId: '',
        file: [],
        commodityMap: [], // 商品图
        materialMap: [], // 素材图
        transparencyDrawing: [], // 透明图
        imageType: '',
        previewShow: false,
        previewObj: {},
        uploadType: '',
        uploadFileList: [],
        needUploadMainImageCount: 0,
        uploadMaterialFileList: [],
        uploadTransFileList: []
      },
      form: {
      },
      rules: {}
    }
  },
  computed: {},
  watch: {
  },
  created() { },
  mounted() {
    this._FUNCTION_NAME = this.$route.name
    this.onInit()
  },
  beforeDestroy() { },
  methods: {
    onInit(data) {
      const self = this
      self.customData.masterItemId = sessionStorage.getItem('itemId')
      const params = {
        masterItemId: sessionStorage.getItem('itemId')
      }
      _api.imageDetail(self, params, self.callBack_imageDetail)
      // 拖拽排序必须写
      self.$dragging.$on('dragged', ({ value }) => { })
      self.$dragging.$on('dragend', () => { })
    },
    onSearch(data) {
      const self = this
    },
    onChangePage(data) {
      const self = this
      self.customData.commodityMap = [] // 商品图
      self.customData.materialMap = [] // 素材图
      self.customData.transparencyDrawing = [] // 透明图
      const params = {
        masterItemId: self.customData.masterItemId
      }
      _api.imageDetail(self, params, self.callBack_imageDetail)
    },
    onReset(data) {
      const self = this
    },
    onAdd(data) { },
    onDelete(data) {
      const self = this
    },
    onInfo(data) {
      const self = this
    },
    onUpdate(formName) {
      const self = this
    },
    onBathDelete() {
      const self = this
    },
    onBathUpdate() { },
    onDisable(data) {
      const self = this
    },
    onEnable(data) {
      const self = this
    },
    onUpload(data) { },
    onBathUpload() { },
    onExport(data) { },
    onDownload(data) { },
    onHistory(data) { },
    callBack_imageDetail(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        if (data.data.length != 0) {
          data.data.forEach(item => {
            if (item.imageType == 2) {
              self.customData.commodityMap.push(item)
            } else if (item.imageType == 4) {
              self.customData.materialMap.push(item)
            }
          })
        }
        if (self.customData.commodityMap.length != 0) {
          const graphUrl = self.customData.commodityMap[0].displayUrl
          self.customData.graphImage = graphUrl
          self.customData.graphImageName = self.customData.commodityMap[0].imageName
        }
      }
    },
    // 图片删除
    callBack_imageDelete(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        if (self.customData.imageType == 5) {
          self.customData.drawingImage == ''
        }
        self.onChangePage()
      }
    },
    // 图片排序
    callBack_imageSort(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        self.dialogData.productBox = false
        self.dialogData.matertBox = false
        _validate.openTip(self, '保存成功', 'success')
        self.onChangePage()
      }
    },
    // 透明图校验
    beforeDrawingUploadType(file, fileList) {
      const self = this
      const imageSort = self.customData.transparencyDrawing.length + fileList.length
      self.fileCheck(file, '5', imageSort)
    },
    // 商品图校验
    beforeCommodityMapUploadType(file, fileList) {
      const self = this
      const imageSort = self.customData.commodityMap.length + fileList.length
      self.fileCheck(file, '2', imageSort)
    },
    // 素材图检验
    beforeMaterialUploadType(file, fileList) {
      const self = this
      const imageSort = self.customData.uploadMaterialFileList.length + fileList.length
      self.fileCheck(file, '4', imageSort)
    },
    // 验证图片大小以及格式
    fileCheck(file, value, imageSort) {
      const self = this
      const extName = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      let AllUpExt
      const isLt10M = file.size / 1024 / 1024 < 1
      if (value === '5') { // 透明图
        AllUpExt = '.png|'
      } else {
        AllUpExt = '.png|.jpg|'
      }
      if (!isLt10M) {
        _validate.openTip(self, '文件大小不能超过1M', 'warning')
        return false
      }
      if (AllUpExt.indexOf(extName + '|') == '-1') {
        _validate.openTip(self, '上传文件格式错误', 'warning')
        return false
      }
      self.proportion(file, value).then(function(data) {
        if (data) {
          self.customData.uploadType = value
          self.itemUpload(file, imageSort)
        }
      })
    },
    // 验证图片比例和图片尺寸
    proportion(file, value) {
      const self = this
      const p = new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file.raw) // 必须用file.raw
        reader.onload = () => { // 让页面中的img标签的src指向读取的路径
          const img = new Image()
          img.src = reader.result
          if (img.complete) { // 如果存在浏览器缓存中
            if (img.width !== img.height) {
              self.$message.warning(`图片比例1：1,当前文件${img.width}×${img.height}`)
              resolve(false)
            } else {
              resolve(true)
            }
          } else {
            img.onload = () => {
              if (value === '5') { // 透明图
                if (img.width != 800 && img.height != 800) {
                  self.$message.warning(`图片的尺寸为800*800px，当前文件${img.width}×${img.height}，请您重新选择`)
                  resolve(false)
                } else {
                  resolve(true)
                }
              } else {
                if (img.width !== img.height) {
                  self.$message.warning(`图片比例为1：1,当前文件${img.width}×${img.height}，请您重新选择`)
                  resolve(false)
                } else {
                  if (img.width > 1000 || img.width < 600 || img.height > 1000 || img.height < 600) {
                    self.$message.warning(`图片的尺寸为600*600 ~ 1000*1000之间，当前文件${img.width}×${img.height}，请您重新选择`)
                    resolve(false)
                  } else {
                    resolve(true)
                  }
                }
              }
            }
          }
        }
      })
      return p
    },
    // 上传
    itemUpload(file, imageSort) {
      const self = this
      const fd = new FormData()
      fd.append('file', file.raw)
      fd.append('masterItemId', self.customData.masterItemId)
      fd.append('imageType', self.customData.uploadType)
      fd.append('imageSort', imageSort)
      const url = process.env.VUE_APP_IMAGE_UPLOAD
      self.customData.needUploadMainImageCount += 1
      global.postupload(url, null, fd, function(response) {
        const res = JSON.parse(response)
        self.customData.needUploadMainImageCount -= 1
        if (res.code != 200) {
          _validate.openTip(self, res.message, 'error')
        } else {
          _validate.openTip(self, '图片上传成功', 'success')
          if (self.customData.needUploadMainImageCount < 1) {
            self.onChangePage()
          }
        }
      },
      function(error) {
        self.$message.error(error)
      }
      )
    },
    // 删除
    removeImg(data, value) {
      const self = this
      self.customData.imageType = value
      const params = {
        masterItemId: self.customData.masterItemId,
        imageId: data.imageId,
        uploadId: data.uploadId
      }
      // 图片类型2：商品图；3：文描图；4：素材图；5：透图 ,
      if (value == 2) {
        params.imageType = 2
      } else if (value == 5) {
        params.imageType = 5
      } else if (value == 4) {
        params.imageType = 4
      }
      _api.imageDelete(self, params, self.callBack_imageDelete)
    },
    addImg(data, value) {
      const self = this
      self.customData.imageType = value
      const params = {
        masterItemId: self.customData.masterItemId,
        imageId: data.imageId,
        uploadId: data.uploadId
      }
      // 图片类型2：商品图；3：文描图；4：素材图；5：透图 ,
      if (value == 2) {
        params.imageType = 2
      } else if (value == 5) {
        params.imageType = 5
      } else if (value == 4) {
        params.imageType = 4
      }
      params.imageSort = self.customData.commodityMap.length + 1
      _api.imageAdd(self, params, self.callBack_imageAdd)
    },
    callBack_imageAdd(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        if (self.customData.imageType == 5) {
          self.customData.drawingImage == ''
        }
        self.onChangePage()
      }
    },
    // 打开预览
    previewImg(data) {
      const self = this
      self.customData.previewObj = data
      self.customData.previewShow = true
    },
    // 关闭预览
    closeDialogs() {
      const self = this
      self.customData.previewObj = {}
      self.customData.previewShow = false
    },

    infoUpdate() {
      const self = this
      const params = {
        imageSorts: self.customData.commodityMap
      }
      _api.imageSort(self, params, self.callBack_imageSort)
    },
    productBox() {
      this.dialogData.productBox = true
    },
    matertBox() {
      this.dialogData.matertBox = true
    }
  }
}
</script>

<style scoped>
.drawing_div{
    border-radius: 6px;
    background-color: #fbfdff;
    width:136px;
    height:136px;
    box-sizing:border-box;
    border:1px dashed #c0ccda;
    display:flex;
    justify-content: center;
    align-items: center;
}
.title{
    font-size: 15px;
}
.buttonWidht{
    width: 100%;
}
/*被拖拽对象的样式*/
.item {
    padding: 6px;
    background-color: #fdfdfd;
    border: solid 1px #eee;
    margin-bottom: 10px;
    cursor: move;
}
/*选中样式*/
.chosen {
    border: solid 2px #3089dc !important;
}
.previewBox span{
    display: flex; flex-wrap: wrap;
}
.mainImgStyle span{
    display: flex; flex-wrap: wrap;
}
</style>
